package jsyf.com.service;

import com.alibaba.fastjson.JSONObject;
import jsyf.com.dao.TAttachmentDao;
import jsyf.com.entity.TAttachment;
import jsyf.com.util.BaseUtils;
import jsyf.com.util.FastDFSClientUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
* @author: @韩武洽 @Wyshown
* @Version: V1.0.0
*/
@Service
@PropertySource("classpath:fastdfs.properties")
public class TAttachmentService {

    @Autowired
    private TAttachmentDao attachmentDao;

	
	@Bean
	public static PropertySourcesPlaceholderConfigurer propertyConfigure(){
		return new PropertySourcesPlaceholderConfigurer();
	}
	
	/**
	 * FASTDFS_BASEURL
	 */
	@Value("${fastdfs.baseurl}")
	public String fastdfsBaseurl;
	
	/**
	* @Description: 方法描述,必填  <br/>
	* @return: java.lang.String
	* @throw:
    * @author: @韩武洽 @Wyshown
    * @Version: V1.0.0
	*/
	public String getId(){
		return this.attachmentDao.generateKey();
	}

	/**
	 * <B>方法名称：</B>文件上传<BR>
	 * <B>概要说明：</B>文件上传<BR>
	 * @return String 错误信息
	 * @throws Exception 输入输出异常
     * @author: @韩武洽 @Wyshown
     * @Version: V1.0.0
	 */
    public JSONObject put(MultipartFile mf,String createdBy,String fileType,String message,String name) throws Exception {
        System.err.println(name);
        /*转换值*/
        String id =this.attachmentDao.generateKey();
        TAttachment att= new TAttachment();
        JSONObject ret = new JSONObject();
        if(createdBy!=null){
            att.setCreatedBy(createdBy);
        }
        if(fileType!=null){
            att.setFileType(fileType);
            ret.put("fileType", fileType);
        }

        if(message!=null){
            att.setRemark(message);
            ret.put("remark",message);
        }

        Date expiresTime = new Date(this.attachmentDao.getCurrentTime() .getTime() + 86400000);

         /**
          * TODO 因为涉及到两个事务控制 fastdfs和数据库 不好控制
          * 所有比较好的做法为在这里记录日志,
          * 防止突然宕机,或者断电,  让文件和数据库记录保持一致性
        */

        /** 文件真实名称*/
        String realName= mf.getOriginalFilename();

        String fileName="";
        if(name != null && "" != name){
          fileName=name;
        }else{
          fileName=realName;
        }
    	String extName = getExtName(realName);/**文件扩展名*/
    	String fileId = FastDFSClientUtils.upload(mf.getBytes(), extName);
    	String dataGroup = fileId.substring(0,fileId.indexOf("/"));
    	String size = String.valueOf( mf.getSize());

    	att.setId(id);
    	att.setFileName(fileName);
    	att.setFileUrl(fileId);
        att.setFileSize(size);
        att.setExtension(extName);
        att.setExpiresTime(expiresTime);
        att.setDataGroup(dataGroup);
        att.setCreatedTime(attachmentDao.getCurrentTime());

        att.setDelFlag("1");
        int result=attachmentDao.insert(att);
        if(result>0){
            ret.put("id", id);
            ret.put("fileName", fileName);
            ret.put("fileSize", mf.getSize());
            ret.put("dataGroup", dataGroup);
            ret.put("expiresTime", expiresTime);
            ret.put("fileUrl", fileId);
            ret.put("fileAllUrl",fastdfsBaseurl+"/" + fileId);
            ret.put("delFlag","1");
            return ret;
        }else{
            return null;
        }
    }

    /**
     * <B>方法名称：</B>上传DATA数据文件<BR>
     * <B>概要说明：</B>上传DATA数据文件<BR>
     * @author: @韩武洽 @Wyshown
     * @Version: V1.0.0
     * @param id 键值
     * @param fileType 分类
     * @param userId 用户标识
     * @param fileName 文件名称
     * @param expiresTime 过期时间
     * @param data 文件数据
     * @param remark 备注信息
     * @return String 错误信息
     * @throws IOException 输入输出异常
     */
    public String put(String id, String fileType, String userId, String fileName, Date expiresTime, byte[] data, String remark)
            throws IOException {

        if(StringUtils.isBlank(fileName)){
            return "没有指定文件名称";
        }
        if (data == null || data.length < 1) {
            return "没有指定文件数据";
        }
        
    	String fileId = FastDFSClientUtils.upload(data, getExtName(fileName));
    	String dataGroup = fileId.substring(0,fileId.indexOf("/"));

        TAttachment att= new TAttachment();
        att.setId(id);
        att.setFileName(fileName);
        att.setFileUrl(fileId);
        att.setFileType(fileType);
        att.setFileSize(String.valueOf(data.length));
        att.setExtension(getExtName(fileName));
        att.setExpiresTime(expiresTime);
        att.setDataGroup(dataGroup);
        att.setCreatedBy(userId);
        att.setCreatedTime(attachmentDao.getCurrentTime());
        att.setRemark(remark);
        att.setDelFlag("1");
        int result=attachmentDao.insert(att);
        if(result>0){
            JSONObject ret = new JSONObject();
            ret.put("id", id);
            ret.put("fileType", fileType);
            ret.put("fileName",fileName);
            ret.put("fileSize", String.valueOf(data.length));
            ret.put("fileUrl", fileId);
            ret.put("fileAllUrl",fastdfsBaseurl+"/" + fileId);
            ret.put("dataGroup", dataGroup);
            ret.put("expiresTime", expiresTime);
            return BaseUtils.succsessObjRespond(ret);
        }else{
            return BaseUtils.errorrRespond("保存数据库失败！");
        }
    }

    /**
     * @param
     * @Description: 清除服务器以及数据库
     * 过期文件 <br/>
     * @return: void
     * @author: 章玄
     * @createTime: 2017/12/5 14:10
     * @Version: V1.0.0
     */

    public void delete() {
        Date date=this.attachmentDao.getCurrentTime();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, -7);
        date = calendar.getTime();
        /*根据时间查询相应的文件信息*/
        List<JSONObject> list=this.attachmentDao.findAllByTimeAndStatus(date);
        /*循环删除服务器的文件*/
        for(int i=0;i<list.size();i++){
            String fileUrl = list.get(i).getString("fileUrl");
            String dataGroup = list.get(i).getString("dataGroup");
            FastDFSClientUtils.delete(dataGroup, fileUrl);
        }
        /*批量删除数据库的文件数据*/
        attachmentDao.deleteBatch(date);
    }


    /**
     * <B>方法名称：</B>系统文件过期<BR>
     * <B>概要说明：</B><BR>
     * @author: @韩武洽 @Wyshown
     * @Version: V1.0.0
     * @param keys 文件键值
     */
    public void expire(String... keys) {
        if (keys == null || keys.length < 1) {
            return;
        }
        if (keys.length == 1) {
            keys = keys[0].split(",");
        }
        for (String key : keys) {
            attachmentDao.expire(key, null);
        }
    }

    /**
     * <B>方法名称：</B>系统文件过期<BR>
     * <B>概要说明：</B><BR>
     * @author: @韩武洽 @Wyshown
     * @Version: V1.0.0
     * @param key 文件键值
     * @param expired 过期时间（null为当前时间）
     */
    public void expire(String key, Date expired) {
        if (StringUtils.isBlank(key)) {
            return;
        }
        String[] keys = key.split(",");
        for (String k : keys) {
            attachmentDao.expire(k, expired);
        }
    }

    /**
     * <B>方法名称：</B>清除系统文件过期限制<BR>
     * <B>概要说明：</B><BR>
     * @author: @韩武洽 @Wyshown
     * @Version: V1.0.0
     * @param keys 文件键值
     */
    public void clearExpired(String... keys) {
        if (keys == null || keys.length < 1) {
            return;
        }
        if (keys.length == 1) {
            keys = keys[0].split(",");
        }
        for (String key : keys) {
            attachmentDao.clearExpired(key);
        }
    }

    /**
     * <B>方法名称：</B>获取文件扩展名<BR>
     * <B>概要说明：</B><BR>
     * @author: @韩武洽 @Wyshown
     * @Version: V1.0.0
     * @param filename 文件名
     * @return String 扩展名
     */
    public String getExtName(String filename) {
        if (StringUtils.isBlank(filename)) {
            return null;
        }
        int i = filename.indexOf(".");
        if (i >= 0) {
            return filename.substring(i + 1).trim().toLowerCase();
        }
        return null;
    }

    /**
     * <B>方法名称：</B>获取系统文件信息<BR>
     * <B>概要说明：</B><BR>
     * @author: @韩武洽 @Wyshown
     * @Version: V1.0.0
     * @param key 文件键值
     * @return TAttachment 系统文件基本信息
     */
   /* public TAttachment getInfo(String key) {
        return attachmentDao.get(key);
    }*/

    /**
     * <B>方法名称：</B>获取系统文件信息列表<BR>
     * <B>概要说明：</B><BR>
     * @author: @韩武洽 @Wyshown
     * @Version: V1.0.0
     * @param keys 文件键值集合
     * @return List<TAttachment> 系统文件信息列表
     */
   /* public List<TAttachment> getInfoList(String... keys) {
        return attachmentDao.getList(keys);
    }	*/
    
    /**
     * <B>方法名称：</B>删除系统文件<BR>
     * <B>概要说明：</B><BR>
     * @author: @韩武洽 @Wyshown
     * @Version: V1.0.0
     * @param keys 文件键值
     */
  /*  public void delete(String... keys) {
        if (keys == null || keys.length < 1) {
            return;
        }
        if (keys.length == 1) {
            keys = keys[0].split(",");
        }
        try {
            for (String key : keys) {
                TAttachment att = attachmentDao.get(key);
//                String fileId = filePath.substring(fastdfsBaseurl.length());
                String groupName = att.getDataGroup();
//                FastDFSClientUtils.delete(groupName, fileId);
//                attachmentDao.delete(key);
                BaseUtils.succsessObjRespond();
            }
        } catch (Exception e) {
            e.printStackTrace();
             BaseUtils.errorrRespond();
        }
    }*/

    /**
     * <B>方法名称：</B>清空文件方法<BR>
     * <B>概要说明：</B>清空文件方法<BR>
     * @return List<String> 文件Key集合
     * @author: @韩武洽 @Wyshown
     * @Version: V1.0.0
     */
/*	public List<String> clearFileKeys(){
		return this.attachmentDao.clearFileKeys();
	}*/
}
